<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>amis admin</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta
            name="viewport"
            content="width=device-width, initial-scale=1, maximum-scale=1"
    />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
    <link rel="stylesheet" href="./jssdk/sdk.css"/>
    <link rel="stylesheet" href="./jssdk/helper.css"/>
    <link rel="stylesheet" href="./jssdk/iconfont.css"/>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
    <script src="./common.js"></script>

    <style>
        html,
        body,
        .app-wrapper {
            position: relative;
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }

        ul.cxd-AppBcn li.cxd-AppBcn-item {
            cursor: default; /* 可选：更改鼠标指针样式 */
            user-select: none;
        }

        li.cxd-AppBcn-item a:not([href]) {
            color: inherit !important; /* 继承父元素颜色 */
            cursor: default; /* 可选：更改鼠标指针样式 */
            user-select: none;
        }
    </style>
</head>
<body>
<div id="root" class="app-wrapper"></div>

<script src="./jssdk/sdk.js"></script>
<script src="https://unpkg.com/vue@2"></script>
<script src="https://unpkg.com/history@4.10.1/umd/history.js"></script>
<script>
    (function () {
        window.enableAMISDebug = true;

        let amis = amisRequire('amis/embed');
        const match = amisRequire('path-to-regexp').match;

        // 如果想用 browserHistory 请切换下这处代码, 其他不用变
        // const history = History.createBrowserHistory();
        const history = History.createHashHistory();

        let amisLib = amisRequire('amis');
        amisLib.registerFilter('splitDefault', function (str, defaultValue = [], delimiter = ",") {
            if (!str || !str.length) {
                return defaultValue;
            }
            return str.split(delimiter);
        });


        const app = {
            id:"app",
            type: 'app',
            brandName: 'NoCoAdmin',
            logo: './img/favicon.png',
            header: {
                "type": "grid",
                "columns": [
                    {
                        "md": 10,
                        "body": ' '

                    },
                    {
                        "md": 2,
                        "columnClassName": "text-right",
                        "body": {
                            size: 'lg',
                            "type": "dropdown-button",
                            "icon": "fa fa-user",
                            "label": '${layout.nick}',
                            "trigger": "hover",
                            "closeOnClick": true,
                            "buttons": [
                                {
                                    "type": "button",
                                    "label": "修改密码",
                                    "actionType": "dialog",
                                    "dialog": {
                                        "title": "修改密码",
                                        "body": {
                                            "type": "form",
                                            "api": {
                                                "url": "/unify/User/updatePassword",
                                                "requestAdaptor": function (api, context) {
                                                    context.oldPassword = CryptoJS.MD5(context.oldPassword).toString();
                                                    context.password = CryptoJS.MD5(context.password).toString();
                                                    context.passwordAgain = CryptoJS.MD5(context.passwordAgain).toString();
                                                }
                                            },
                                            "body": [
                                                {
                                                    "type": "input-password",
                                                    "name": "oldPassword",
                                                    "label": "旧密码：",
                                                    "required": true,
                                                },
                                                {
                                                    "type": "input-password",
                                                    "name": "password",
                                                    "label": "新密码：",
                                                    "required": true,
                                                },
                                                {
                                                    "name": "passwordAgain",
                                                    "type": "input-password",
                                                    "label": "确认密码：",
                                                    "required": true,
                                                }
                                            ]
                                        }
                                    }
                                },
                                {
                                    "type": "button",
                                    "label": "退出登录",
                                    "onEvent": {
                                        "click": {
                                            "actions": [
                                                {
                                                    "actionType": 'ajax',
                                                    "api": "/unify/User/logout"
                                                },
                                                {
                                                    "actionType": "custom",
                                                    "script": "(context,doAction,event)=>{localStorage.remove('user_token')}"
                                                },
                                                {
                                                    "actionType": "url",
                                                    "args": {
                                                        "url": "/login.html",
                                                        "blank": false,
                                                    }
                                                }
                                            ]
                                        }
                                    }
                                }
                            ],
                            "visibleOn": '${layout.nick.length > 0}'
                        }
                    }
                ]
            },
            showFullBreadcrumbPath: true,
            // showBreadcrumb:false,
            footer: '<div class="p-2 text-center bg-light">© 2025 NoCoAdmin. All rights reserved. <a href="https://beian.miit.gov.cn/" target="_blank">浙ICP备2024100632号-4</a></div>',
            // asideBefore: '<div class="p-2 text-center">菜单前面区域</div>',
            // asideAfter: '<div class="p-2 text-center">菜单后面区域</div>',
            api: {
                url: '/unify/User/current',
                method: 'post',
                silent: true,
                adaptor: function (payload) {
                    if (payload.code !== 200) {
                        location.href = "/login.html";
                    }
                    return {
                        pages: pagesAdaptor(payload.data.menuList),
                        layout: payload.data
                    };
                },
            }
        };

        window._multiObjPropsToList = function (obj, props = [], keyName = "value", valueName = "label") {
            props.forEach(function (prop) {
                obj[prop] = _objToList(obj[prop], keyName, valueName);
            })

            return obj;
        }
        window._objToList = function (obj, keyName = "value", valueName = "label") {
            let list = [];
            Object.keys(obj).forEach(function (key) {
                list.push({[keyName]: key, [valueName]: obj[key]});
            })
            return list;
        }

        function normalizeLink(to, location = history.location) {
            to = to || '';

            if (to && to[0] === '#') {
                to = location.pathname + location.search + to;
            } else if (to && to[0] === '?') {
                to = location.pathname + to;
            }

            const idx = to.indexOf('?');
            const idx2 = to.indexOf('#');
            let pathname = ~idx
                ? to.substring(0, idx)
                : ~idx2
                    ? to.substring(0, idx2)
                    : to;
            let search = ~idx ? to.substring(idx, ~idx2 ? idx2 : undefined) : '';
            let hash = ~idx2 ? to.substring(idx2) : location.hash;

            if (!pathname) {
                pathname = location.pathname;
            } else if (pathname[0] != '/' && !/^https?\:\/\//.test(pathname)) {
                let relativeBase = location.pathname;
                const paths = relativeBase.split('/');
                paths.pop();
                let m;
                while ((m = /^\.\.?\//.exec(pathname))) {
                    if (m[0] === '../') {
                        paths.pop();
                    }
                    pathname = pathname.substring(m[0].length);
                }
                pathname = paths.concat(pathname).join('/');
            }

            return pathname + search + hash;
        }

        function isCurrentUrl(to, ctx) {
            if (!to) {
                return false;
            }
            const pathname = history.location.pathname;
            const link = normalizeLink(to, {
                ...location,
                pathname,
                hash: ''
            });

            if (!~link.indexOf('http') && ~link.indexOf(':')) {
                let strict = ctx && ctx.strict;
                return match(link, {
                    decode: decodeURIComponent,
                    strict: typeof strict !== 'undefined' ? strict : true
                })(pathname);
            }

            return decodeURI(pathname) === link;
        }


        function pagesAdaptor(menuList) {
            function pageAdaptor(menu) {
                let page = {
                    label: menu.title,
                    icon: menu.icon,
                    children: [],
                };
                switch (menu.type) {
                    case 'group':
                        break;
                    case 'menu_page':
                        page.url = menu.url;
                        page.schemaApi = "get:" +menu.url + ".json";
                        break;
                    case 'page':
                        page.url = menu.url;
                        page.schemaApi = "get:" + menu.url +".json";
                        page.visible = false;
                        break;
                    case 'menu_link':
                        if (menu.target === "_self") {
                            page.url = menu.url;
                            page.schemaApi = "get:" + menu.url +"/pages/unify/iframe/index.json";
                        } else {
                            page.link = menu.url;
                        }
                        break;
                }

                return page;
            }

            var pages = [];
            menuList.map(function (firstMenu) {
                var firstPage = pageAdaptor(firstMenu);
                if (firstMenu.children) {
                    firstMenu.children.map(function (secondMenu) {
                        var secondPage = pageAdaptor(secondMenu);
                        if (secondMenu.children) {
                            secondMenu.children.map(function (thirdMenu) {
                                secondPage.children.push(pageAdaptor(thirdMenu));
                            });
                        }
                        firstPage.children.push(secondPage);
                    });
                }
                pages.push({children: [firstPage]});
            });

            // pages[0].label = "导航";
            pages.unshift({
                children: [{
                    label: "首页",
                    url: "/",
                    schemaApi: "/pages/unify/index.json",
                }]
            })
            console.log(pages);
            return pages;
        }

        let amisInstance = amis.embed(
            '#root',
            app,
            {
                location: history.location,
                data: {
                    // 全局数据，是受控的数据
                },
                context: {
                    USER_TOKEN: localStorage.getItem("user_token")
                    // 全局上下文数据, 非受控的数据，无论哪一层都能获取到，包括弹窗自定义数据映射后都能获取到。
                    // 可以用来放一下全局配置等。比如 API_HOST, 这样页面配置里面可以通过 ${API_HOST} 来获取到。
                }
            },
            {
                requestAdaptor(api) {
                    api.headers.Authorization = 'bearer ' + localStorage.getItem('user_token');
                    if (!api.method) {
                        api.method = "post";
                    }
                    if (!/\.json($|\?|#)/i.test(api.url)) {
                        api.url = WEBSITE_HOST + api.url;
                    }
                    return api;
                },
                responseAdaptor(api, payload, query, request, response) {
                    if (/\.json($|\?|#)/i.test(api.url)) {
                        return payload;
                    }
                    payload.status = payload.code === 200 ? 0 : payload.code;
                    return payload;
                },
                // watchRouteChange: fn => {
                //   return history.listen(fn);
                // },
                updateLocation: (location, replace) => {
                    location = normalizeLink(location);
                    if (location === 'goBack') {
                        return history.goBack();
                    } else if (
                        (!/^https?\:\/\//.test(location) &&
                            location ===
                            history.location.pathname + history.location.search) ||
                        location === history.location.href
                    ) {
                        // 目标地址和当前地址一样，不处理，免得重复刷新
                        return;
                    } else if (/^https?\:\/\//.test(location) || !history) {
                        return (window.location.href = location);
                    }

                    history[replace ? 'replace' : 'push'](location);
                },
                jumpTo: (to, action) => {
                    if (to === 'goBack') {
                        return history.goBack();
                    }

                    to = normalizeLink(to);

                    if (isCurrentUrl(to)) {
                        return;
                    }

                    if (action && action.actionType === 'url') {
                        action.blank === false
                            ? (window.location.href = to)
                            : window.open(to, '_blank');
                        return;
                    } else if (action && action.blank) {
                        window.open(to, '_blank');
                        return;
                    }

                    if (/^https?:\/\//.test(to)) {
                        window.location.href = to;
                    } else if (
                        (!/^https?\:\/\//.test(to) &&
                            to === history.pathname + history.location.search) ||
                        to === history.location.href
                    ) {
                        // do nothing
                    } else {
                        history.push(to);
                    }
                },
                isCurrentUrl: isCurrentUrl,
                theme: 'cxd'
            }
        );

        history.listen(state => {
            amisInstance.updateProps({
                location: state.location || state
            });
        });
    })();
</script>
</body>
</html>
